<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /* 防抖 */   /* 输入框搜索，按钮点击，窗口调整 */
    /* 节流 */   /* 页面滚动、鼠标移动、滑动加载 */

    // 在 setTimeOut 和 setTimeInterval 里面使用clearTimeout 或者 clearInterval 不是一个明智的选择， 使用 timer = null
    /* 防抖 */
    function debounce(func, delay){
      let timer = null
      return function(...args) {
        if(timer) {
        
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          func.apply(this,args)
        },delay)
      }
    }

    const a = debounce(function(a,  b) {
      console.log('🚀 ~ This is a result of console.log ~ ✨: ', arguments, this);
    }, 1000)
    a(1, 2)

    function debounce(func, delay) {
      let timer = null
      return function(...args){
        console.log('🚀 ~ This is a result of console.log ~ ✨: ', this);
        if(timer) {
          clearInterval(timer)
        }
        timer = setTimeout(() => {
          func.apply(this,args)
        },delay)
      }
    }
    /* 节流 */
    /* 1.时间戳实现 */

    function throttle(func, delay) {
      let prev = 0
      return function(...args){
        let now = new Date()
        if(now - prev >= delay){
          prev = now
          func.apply(this, args)
        }
      }
    }

    /* 定时器实现 */
    function throttle(func, delay) {
      let timer = null
      return function(...args) {
        if(!timer){
          timer = setTimeout(() => {
            func.apply(this, args)
            timer = null
          },delay)
        }
      }
    }
  </script>
</body>
</html>
